#include <iostream>
#include <pthread.h>
#include <string>
#include <functional>
namespace mythread
{
    static int count = 1;
    using func = std::function<void(void)>;
    static int _default = 1;
    class thread
    {
        static void *rontinue(void *args)
        {
            thread *td = static_cast<thread *>(args);
            td->_fun();
            return (void *)"new threat return";
        }
        void EnableRun() { _runing = true; }
        void EnableDetach() { _detach = true; }

    public:
        thread(func fun) : _tid(_default), _detach(false), _runing(false), _fun(fun), _retval(nullptr)
        {
            _name = "thread-" + std::to_string(count);
            count++;
        }
        void Start()
        {
            if (_runing)
                return;
            int n = pthread_create(&_tid, nullptr, rontinue, this);
            if (n != 0)
            {
                std::cerr << "pthread_create" << std::endl;
                exit(1);
            }
            Detach();
            EnableRun();
        }
        void Detach()
        {
            if (_runing)
                pthread_detach(_tid);
            EnableDetach();
        }
        void Cancel()
        {
            if (_runing == false)
                return;
            pthread_cancel(_tid);
            _runing = false;
        }
        void Join()
        {
            if (_detach)
                return;
            pthread_join(_tid, &_retval);
        }
        ~thread()
        {
            Cancel();
            Join();
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _detach;
        bool _runing;
        func _fun;
        void *_retval;
    };

}